package com.wbs.batis.rest;

import com.wbs.batis.rest.annotation.EnableRestMapper;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class MapperComponentScanAndRegister implements ApplicationListener<ContextRefreshedEvent> {


    RestInterfaceRegister restInterfaceRegister;

    SqlSessionTemplate sqlSessionTemplate;

    public MapperComponentScanAndRegister(RestInterfaceRegister restInterfaceRegister, SqlSessionTemplate sqlSessionTemplate) {
        this.restInterfaceRegister = restInterfaceRegister;
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        sqlSessionTemplate.getConfiguration().getMapperRegistry().getMappers().forEach(mapperCls -> {
            if(mapperCls.getAnnotation(EnableRestMapper.class) != null){
                restInterfaceRegister.register(mapperCls);
            }
        });

    }
}
